package com.gjs.cd.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gjs.cd.mapper.CdResourceMapper;
import com.gjs.cd.pojo.dto.CdResourceReq;
import com.gjs.cd.pojo.dto.TotalReq;
import com.gjs.cd.pojo.entity.CdResource;
import com.gjs.cd.service.ICdResourceService;
import com.gjs.common.microservice.api.IResourceMicroService;
import com.gjs.common.pojo.dto.request.PageQuery;
import com.gjs.common.pojo.dto.resource.TypeDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toMap;

/**
 * @author zhongwenguang
 * @date 2022-3-16 11:17
 */
@Service
public class CdResourceServiceImpl extends ServiceImpl<CdResourceMapper, CdResource> implements ICdResourceService {

    @DubboReference
    private IResourceMicroService iResourceMicroService;

    @Autowired
    private CdResourceMapper cdResourceMapper;

    @Override
    public IPage<CdResourceReq> getListByCdId(PageQuery pageQuery,Long cdId) {
        //通过cdId查询CdResource表
        LambdaQueryWrapper<CdResource> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(CdResource::getCdId,cdId);
        IPage<CdResource> cdResourceIPage = this.page(pageQuery.buildPage(),lambdaQueryWrapper);
        //获取resource_id - resource_name
        List<TypeDTO> subjectsList = iResourceMicroService.listSubjects();
        Map<Long,String> subjectMap = subjectsList.stream().collect(toMap(TypeDTO::getKey,TypeDTO::getText));
        //转换并赋值（subjectName）
        IPage<CdResourceReq> cdResourceReqIPage = cdResourceIPage.convert(u->{
            CdResourceReq v = new CdResourceReq();
            BeanUtil.copyProperties(u,v);
            v.setResourceName(subjectMap.get(u.getResourceId()));
            return v;
        });
        return cdResourceReqIPage;
    }

    @Override
    public List<TotalReq> getTotalByIds(List<Long> ids) {
        List<TotalReq> list = cdResourceMapper.getTotalByIds(ids);
        return list;
    }
}
